package entity

import (
	"errors"
	"fmt"

	"shqsoft.cn/pas3ui/base"

	"gorm.io/gorm"
)

type SysRole struct {
	RoleId   int    `gorm:"AUTO_INCREMENT;primary_key;column:RoleId"`
	RoleName string `gorm:"column:RoleName"`
	IsSys    bool   `gorm:"column:IsSys"`
	RoleDes  string `gorm:"column:RoleDes"`
	Perms    string `gorm:"column:Perms"`
}

//TableName Role 角色表名
func (SysRole) TableName() string {
	return "t_Role"
}
func (o *SysRole) BeforeCreate(tx *gorm.DB) (err error) {
	var count int64
	err = tx.Model(SysRole{}).Where(&SysRole{RoleName: o.RoleName}).Count(&count).Error
	if err != nil {
		return err
	}
	if count > 0 {
		info := fmt.Sprintf("角色名称 '%s' 已存在，请修改！", o.RoleName)
		return errors.New(info)
	}
	return
}
func (r *SysRole) BeforeUpdate(tx *gorm.DB) (err error) {
	if r.RoleId == 15 || r.RoleId == 16 {
		return errors.New("系统角色不允许修改！")
	}
	return
}

// BeforeDelete 有认定关系，不允许删除员工
func (r *SysRole) BeforeDelete(tx *gorm.DB) (err error) {
	if r.RoleId == 15 || r.RoleId == 16 {
		return errors.New("系统角色不允许删除！")
	}
	msg, err := r.hasRole(tx)
	if err != nil {
		return err
	}
	if msg != "" {
		return fmt.Errorf("%s，不能删除！", msg)
	}
	return
}
func (r *SysRole) hasRole(tx *gorm.DB) (msg string, err error) {
	var count int
	row := tx.Raw(`SELECT COUNT(*) FROM "t_RolePermission" WHERE "RoleId"=?`, r.RoleId).Row()
	err = row.Scan(&count)
	if err != nil {
		return
	}
	if count > 0 {
		msg = "角色已授予页面权限"
		return
	}
	row = tx.Raw(`SELECT COUNT(*) FROM "t_UserRole" WHERE "RoleId"=?`, r.RoleId).Row()
	err = row.Scan(&count)
	if err != nil {
		return
	}
	if count > 0 {
		msg = "角色已授予员工"
		return
	}
	return
}
func SysRoleEF() base.EntityFunc {
	return func() interface{} {
		entity := SysRole{}
		return &entity
	}
}
func SysRoleESF() base.EntitiesFunc {
	return func() interface{} {
		var entities []SysRole
		return &entities
	}
}

func init() {
	base.DaoPoolObj.Put("SysRole", base.NewDefaultDao(SysRoleEF(), SysRoleESF(), nil, "my"))
}
